package cn.edu.scnu.controller;

import cn.edu.scnu.config.RegsterRespone;
import cn.edu.scnu.entity.Member;
import cn.edu.scnu.service.MemberService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MemberController {
    @Autowired
    private MemberService memberService;

    /**
     * 登录操作
     * @param loginData
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginData, HttpSession session) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        Map<String, Object> response = new HashMap<>();

        Member member = memberService.getMemberByUsername(username);
        if (member == null) {
            response.put("success", false);
            response.put("message", "不存在该账号！");
        } else if (!member.getPassword().equals(password)) {
            response.put("success", false);
            response.put("message", "密码与账号不匹配！");
        } else {
            // 登录成功，将用户信息存储到session中
            session.setAttribute("member", member);
            response.put("success", true);
            response.put("member", member);
        }

        return response;
    }

    /**
     * 注册操作
     * @param member
     * @param session
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Member member, HttpSession session) {
        try {
            Member existingMember = memberService.getMemberByUsername(member.getUsername());
            if (existingMember != null) {
                return ResponseEntity.badRequest().body(new RegsterRespone(false, "该用户名已被注册！"));
            }
            memberService.save(member);
            session.setAttribute("member", member);
            return ResponseEntity.ok(new RegsterRespone(true, "注册成功！"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new RegsterRespone(false, e.getMessage()));
        }
    }

    /**
     * 退出操作
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession session) {
        session.removeAttribute("member");
        return ResponseEntity.ok().body(new HashMap<String, String>() {{
            put("message", "退出成功！");
        }});
    }
}
